package com.edu.buservice.biz.handler.strategy;

import cn.dev33.satoken.config.SaCookieConfig;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.edu.buservice.biz.UserManger;
import com.edu.buservice.biz.model.RequestContext;
import com.edu.buservice.dal.model.SysUsers;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.buservice.util.model.enums.ErrorCodeEnum;
import com.edu.buservice.util.model.error.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: KQAIA
 * @description: 普通账号密码登录
 * @author: 无恙
 * @create: 2025-03-07 23:15
 **/
@Slf4j
@Component("normalLogin")
public class NormalLogin extends AbstractLoginImpl{

	@Autowired
	private UserManger userManger;

	@Override
	public void preLogin(RequestContext context) {
		log.info("普通账号密码登录");
		Map<String, String> params = context.getParams();

		if (!params.containsKey("phone") || !params.containsKey("password")){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR,"账号密码不能为空！");
		}

		context.setPhone(params.get("phone"));

		//如果有租户加上租户
		if (params.containsKey("tenantId")){
			TenantUtil.setCurrentTenantId(params.get("tenantId"));
			context.setTenantId(params.get("tenantId"));
		}

	}

	@Override
	public void doLogin(RequestContext context) {

		Map<String, String> params = context.getParams();

		//获取手机号
		String phone = params.get("phone");

		//获取密码
		String password = params.get("password");

		List<SysUsers> userInfo = userManger.getUserInfoByPhone(phone);

		if(Objects.isNull(userInfo)){
			throw new BizException(ErrorCodeEnum.USER_NOT_FOUND);
		}

		SysUsers sysUsers = userInfo.get(0);

		if(sysUsers.getStatus() == 2){
			throw new BizException(ErrorCodeEnum.ACCOUNT_LOCKED);
		}

		String decryptPassword = SecureUtil.md5(password);

		if (!sysUsers.getPassword().equals(decryptPassword)){
			throw new BizException(ErrorCodeEnum.PASSWORD_ERROR);
		}

		StpUtil.login(sysUsers.getUserId());
		context.setUserId(sysUsers.getUserId());

	}
}
